/**
 * Created by bdbs on 2017/6/19.
 */
const electron = require('electron');
const { app, BrowserWindow, Menu, ipcMain } = electron;
const { ADD_TODO, REMOVE_TODO } = require('./ipcTodo.js');

let mainWindow;
let addTodoWindow;

app.on('ready', () => {
  mainWindow = new BrowserWindow({});
  mainWindow.loadURL(`file://${__dirname}/index.html`);
  mainWindow.on('closed', () => app.quit());

  const mainMenu = Menu.buildFromTemplate(mainMenuTemplate);
  Menu.setApplicationMenu(mainMenu);

  addTodoWindow = new BrowserWindow({
    width: 300,
    height: 200,
    show: false,
    title: 'add todo',
  });
  addTodoWindow.loadURL(`file://${__dirname}/addTodo.html`);
});

ipcMain.on(ADD_TODO, (event, todo) => {
  mainWindow.webContents.send('ADD_TODO', todo);
  addTodoWindow.hide();
})

const mainMenuTemplate = [
  {
    label: 'Edit',
    submenu: [
      {
        label: 'addTodo',
        accelerator: 'Command+Shift+A',
        click() {
          addTodoWindow.show();
        }
      },
      {
        label: 'removeTodo',
        accelerator: 'Command+Shift+R',
        click() {
          mainWindow.webContents.send(REMOVE_TODO);
          addTodoWindow.hide();
        }
      }
    ]
  },
];

if (process.platform === 'darwin') {
  mainMenuTemplate.unshift({
    label: 'todos',
    submenu: [
      {
        label: 'quit',
        click() {
          app.quit();
        },
      }
    ]
  });
}

if (process.env.NODE_ENV !== 'production') {
  mainMenuTemplate.push({
    label: 'Developer',
    submenu: [
      { role: 'reload' },
      {
        label: 'dev tool',
        accelerator: process.platform === 'darwin' ? 'Command+Alt+J' : 'Crtl+Alt+j',
        click(item, focusWindow) {
          focusWindow.toggleDevTools();
        },
      },
    ],
  });
}
